﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Globalization;
using System.Collections;
using System.Diagnostics;
using System.Net;

namespace Alchemy_list
{
    public partial class Form1 : Form
    {
        Dictionary<String, items> ItemData = new Dictionary<String, items>();
        String ListAbout;
        String filename;
        Boolean edit = false;
        System.Diagnostics.Stopwatch timer1 = new Stopwatch();

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            load();
            timer1.Start();
        }
        void load()
        {
            if (File.Exists("itemlist.csv"))
            {
                try
                {
                    Stopwatch sw = new Stopwatch();
                    sw.Start();
                    ArrayList lines = new ArrayList();
                    lines.AddRange(File.ReadAllLines("itemlist.csv"));
                    ListAbout = lines[0].ToString();
                    lines.RemoveAt(0);
                    lines.Sort();
                    ArrayList items = new ArrayList();
                    items.Add("Starter");
                    foreach (String line in lines)
                    {
                        String[] info = line.Split(";".ToCharArray());
                        items item = new items();
                        if (info[1] == "starter") item.done = true;
                        items.Add(CultureInfo.CurrentCulture.TextInfo.ToTitleCase(info[0]));
                        item.A = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(info[1]);
                        item.B = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(info[2]);
                        ItemData.Add(CultureInfo.CurrentCulture.TextInfo.ToTitleCase(info[0]), item);
                    }
                    sw.Stop();
                    toolStripStatusLabel2.Text = "List loaded in " + sw.Elapsed.TotalMilliseconds + "ms";
                    foreach (KeyValuePair<string, items> kvp in ItemData)
                    {
                        if (!items.Contains(kvp.Value.A))
                            MessageBox.Show("Error @ '" + kvp.Key + "': '" + kvp.Value.A + "'is not a value item.", "Load error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        if (!items.Contains(kvp.Value.B))
                            MessageBox.Show("Error @ '" + kvp.Key + "': '" + kvp.Value.B + "'is not a value item.", "Load error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    update();
                    edit = false;
                }
                catch (Exception x)
                {
                    MessageBox.Show(x.Message);
                    Close();
                }
            }
            else {
                DialogResult result = MessageBox.Show("Element list not found, download now?", "No list found", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (result == System.Windows.Forms.DialogResult.Yes)
                {
                    download();
                    load();
                }
                else
                {
                    MessageBox.Show("No element list, clossing...", "Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                    Close();
                }
            }
        }

        void download()
        {
            WebClient Client = new WebClient();
            try
            {
                Client.DownloadFile("http://alchemy-cheat-tool.googlecode.com/svn/trunk/itemlist.csv", "itemlist.csv");
                MessageBox.Show("Download successful\r\n\r\n\r\n"+File.ReadAllLines("itemlist.csv")[0].ToString().Replace(";", "\r\n"));
            }
            catch (Exception E)
            {
                MessageBox.Show(E.Message);
            }
        }

        void update()
        {
            ArrayList itemsdone = new ArrayList();
            itemsdone.Add("Starter");
            foreach (KeyValuePair<string, items> kvp in ItemData)
            {
                if (kvp.Value.done == true)
                    itemsdone.Add(kvp.Key);
            }
            toolStripStatusLabel1.Text = itemsdone.Count-1 + "/" + ItemData.Count;
            toolStripProgressBar1.Maximum = ItemData.Count;
            toolStripProgressBar1.Value = itemsdone.Count - 1;
            if (itemsdone.Count-1 == ItemData.Count) MessageBox.Show("Congratulations, all elements are created​​.", "Done", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
            listView1.Items.Clear();
            foreach (KeyValuePair<string, items> kvp in ItemData)
            {
                if (kvp.Value.done != true && itemsdone.Contains(kvp.Value.A) && itemsdone.Contains(kvp.Value.B))
                    kvp.Value.can = true;
                ListViewItem lvi = new ListViewItem(kvp.Key);
                if (kvp.Value.can == true) lvi.BackColor = Color.Orange;
                if (kvp.Value.done == true) lvi.BackColor = Color.Green;
                lvi.SubItems.Add(kvp.Value.A);
                lvi.SubItems.Add(kvp.Value.B);
                listView1.Items.Add(lvi);
            }
            label2.Text = "-";
            label4.Text = "-";
            label6.Text = "-";
            label10.Text = "-";
            label11.Text = "-";
            label7.Text = "-";
            label15.Text = "-";
            label16.Text = "-";
            label12.Text = "-";
            foreach (KeyValuePair<string, items> kvp in ItemData)
            {
                if (kvp.Value.can && !kvp.Value.done)
                {
                    label2.Text = kvp.Value.A;
                    label4.Text = kvp.Value.B;
                    label6.Text = kvp.Key;
                    itemsdone.Add(kvp.Key);
                    break;
                }
            }
            foreach (KeyValuePair<string, items> kvp in ItemData)
            {
                if (itemsdone.Contains(kvp.Value.A) && itemsdone.Contains(kvp.Value.B) && !kvp.Value.done && kvp.Key != label6.Text)
                {
                    label10.Text = kvp.Value.A;
                    label11.Text = kvp.Value.B;
                    label7.Text = kvp.Key;
                    itemsdone.Add(kvp.Key);
                    break;
                }
            }
            foreach (KeyValuePair<string, items> kvp in ItemData)
            {
                if (itemsdone.Contains(kvp.Value.A) && itemsdone.Contains(kvp.Value.B) && !kvp.Value.done && kvp.Key != label6.Text && kvp.Key != label7.Text)
                {
                    label15.Text = kvp.Value.A;
                    label16.Text = kvp.Value.B;
                    label12.Text = kvp.Key;
                    break;
                }
            }
            edit = true;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (timer1.ElapsedMilliseconds > 200)
            {
                foreach (KeyValuePair<string, items> kvp in ItemData)
                {
                    if (kvp.Value.can)
                        if ((label2.Text == kvp.Value.A || label2.Text == kvp.Value.B) && (label4.Text == kvp.Value.A || label4.Text == kvp.Value.B))
                            kvp.Value.done = true;
                }
                ItemData[label6.Text].done = true;
                update();
                timer1.Restart();
            }
        }

        private void markAsDoneToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (listView1.SelectedItems.Count > 0)
            {
                foreach (ListViewItem lvi in listView1.SelectedItems)
                {
                    ItemData[lvi.Text].done = !ItemData[lvi.Text].done;
                }
                update();
            }
        }

        private void newToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ItemData.Clear();
            load();
        }

        private void saveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (String.IsNullOrEmpty(filename))
            {
                DialogResult result = saveFileDialog1.ShowDialog();
                if (result == System.Windows.Forms.DialogResult.OK)
                {
                    if (Save(saveFileDialog1.FileName)) filename = saveFileDialog1.FileName;
                }
            }
            else Save(filename);
        }

        private void saveasToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            DialogResult result = saveFileDialog1.ShowDialog();
            if (result == System.Windows.Forms.DialogResult.OK)
            {
                if (Save(saveFileDialog1.FileName)) filename = saveFileDialog1.FileName; 
            }
        }

        private bool Save(string filename)
        {
            try
            {
                StreamWriter file = new StreamWriter(filename);
                foreach (KeyValuePair<string, items> kvp in ItemData)
                {
                    if (kvp.Value.done == true) file.WriteLine(kvp.Key);
                }

                file.Close();
                edit = false;
                toolStripStatusLabel2.Text = DateTime.Now.ToLongTimeString() + ", Saved progress file";
                return true;
            }
            catch (Exception x)
            {
                MessageBox.Show(x.Message);
                return false;
            }
        }

        private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach (items item in ItemData.Values)
                item.done = false;
            DialogResult result = openFileDialog1.ShowDialog();
            if (result == System.Windows.Forms.DialogResult.OK)
            {
                try
                {
                    String[] lines = File.ReadAllLines(openFileDialog1.FileName);
                    foreach (String line in lines)
                    {
                        if (!string.IsNullOrEmpty(line) && ItemData.ContainsKey(line))
                            ItemData[line].done = true;
                    }
                    toolStripStatusLabel2.Text = DateTime.Now.ToLongTimeString() + ", Readed progress file";
                    filename = openFileDialog1.FileName;
                }
                catch (Exception x)
                {
                    MessageBox.Show(x.Message);
                }
                update();
                edit = false;
            }
            
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            (new AboutBox1(ListAbout)).ShowDialog();
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (edit)
            {
                DialogResult result = MessageBox.Show("Do you want to save progress?", "Save", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
                if (result == DialogResult.Cancel) e.Cancel = true;
                else if (result == DialogResult.Yes)
                {
                    if (String.IsNullOrEmpty(filename))
                    {
                        if (saveFileDialog1.ShowDialog() == DialogResult.OK)
                        {
                            e.Cancel = !Save(saveFileDialog1.FileName);
                        }
                    }
                    else e.Cancel = !Save(filename);
                }
            }
        }

        private void toolStripMenuItem3_Click(object sender, EventArgs e)
        {
            download();
        }

        private void toolStripMenuItem5_Click(object sender, EventArgs e)
        {
            ToolStripItem item = (ToolStripItem)sender;

        }
    }

    public class items
    {
        public Boolean done = false;
        public Boolean can = false;
        public String A = "";
        public String B = "";
    }
}
